//
//  YRMainViewController.swift
//  YR 微博
//
//  Created by cyr on 15/10/8.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

class YRMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
    }

    // 设置自定义按钮的位置
    private func setupComposeButton(){
        let width = tabBar.bounds.width / CGFloat(viewControllers!.count)
        
        let rect = CGRect(x: 0, y: 0, width: width, height: tabBar.bounds.height)
        
        composeButton.frame = CGRectOffset(rect, 2 * width, 0)
    
    }
    
    /**
    点击中间的 + 按钮
    */
    func clickComposeButton() {
        let vc = YRUserAccount.userLogon ? YRComposeViewController() : YROAuthViewController()
        
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
    }
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        setupComposeButton()
    }
    
    private func addChildViewControllers() {
        
        addChildViewController(YRHomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(YRMessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(YRDiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(YRProflieTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    // 懒加载按钮
    lazy private var composeButton: UIButton = {
        
        let button = UIButton()
        
        // 设置自定义按钮的内容
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        
        // 把按钮添加到 tabBar 上
        self.tabBar.addSubview(button)
        
        // 监听按钮的点击
        button.addTarget(self, action: "clickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
    

}
